﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;

namespace Alertatics
{
    public partial class MainPage : PhoneApplicationPage
    {
        string baseUri = "http://alertatics.comule.com/api.php?";
        WebClient client = new WebClient();
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            client.DownloadStringCompleted +=
                new DownloadStringCompletedEventHandler(
                client_DownloadStringCompleted);
        }

        private void SOSButton_Click(object sender, RoutedEventArgs e)
        {   //code=4c250b269746d9b34b22cf4f5bf11b9fe51282e5
            //token=4c250b269746d9b34b22cf4f5bf11b9fe51282e5
            client.DownloadStringAsync(new Uri(baseUri + "USRCODE=" + IsolatedStorageSettings.ApplicationSettings["USRCODE"] + "&TOKEN=" + IsolatedStorageSettings.ApplicationSettings["TOKEN"] + "&OP=help"));
        }
        public void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                string res = e.Result;
                int index = res.IndexOf("}");
                res = res.Substring(0, index + 1);
                string success = res.Substring(res.IndexOf("\"success\":") + 10, 1);
                string error = res.Substring(res.IndexOf("\"error\":") + 8);
                error = error.Replace("\"", "").Replace("}", "");
                if (error == "0" && success == "1")
                {
                    //alert sent
                }
                else
                {
                    //error management
                }
            }
            else
            {
                //error management
                string error = e.Error.Message;
            }
        }

        private void ConfigButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Configuration.xaml", UriKind.Relative));
        }
    }
}